﻿#include "PropPickerCallbackHander.h"

#include <vtkPropPicker.h>
#include <vtkSmartPointer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderWindow.h>
#include <vtkRendererCollection.h>
#include <QMetaObject>
#include <vtkProp.h>
#include <QDebug>

#include <vtkMapper.h>
#include <vtkActor.h>
#include <vtkDataSet.h>
#include <vtkCellPicker.h>
#include <vtkPolyDataMapper.h>
#include <vtkSphereSource.h>
#include <vtkBillboardTextActor3D.h>
#include <vtkTextProperty.h>
#include <vtkNamedColors.h>
#include <vtkPointPicker.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkExtractCells.h>
#include <vtkFeatureEdges.h>
#include <vtkProperty.h>
#include <vtkUnstructuredGrid.h>
#include <vtkDataSetMapper.h>
#include <vtkGeometryFilter.h>

namespace pst
{
    void PropPickerCallbackHander::Execute(vtkObject* caller, unsigned long, void*)
    {
        vtkRenderWindowInteractor* interactor = static_cast<vtkRenderWindowInteractor*>(caller);
        int* clickPos = interactor->GetEventPosition();
        auto renderer = interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer();
        vtkSmartPointer<vtkPropPicker> picker = vtkSmartPointer<vtkPropPicker>::New();

        picker->PickFromListOn();

        for (auto i : PropMap.keys())
        {
            picker->AddPickList(i);
        }


        if (0 != picker->Pick(clickPos[0], clickPos[1], 0, interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()))
        {
            vtkProp* pickedProp = picker->GetViewProp();
            if (pickedProp)
            {
                for (auto it = PropMap.begin(); it != PropMap.end(); ++it)
                {
                    if (it.key() == pickedProp)
                    {
                        ObjectSlot os = it.value();
                        auto callbackObject = os.object;
                        auto callbackSlot = os.slot;
#ifdef _DEBUG
                        qDebug() << "\n"
                            << "CallbackInfo begin====== ";
                        pickedProp->PrintHeader(std::cout, vtkIndent{});
                        qDebug() << "callbackObject = " << callbackObject << "\n"
                            << "callbackSlot = " << callbackSlot;
                        qDebug() << "CallbackInfo begin====== " << "\n";
#endif
                        if (callbackObject != nullptr && callbackSlot != nullptr)
                        {
                            QMetaObject::invokeMethod(callbackObject, callbackSlot, Q_ARG(vtkProp*, pickedProp));
                        }
                    }
                }
            }
        }

        return;
    }

    void PropPickerCallbackHander::addCallbackObjectSlot(vtkProp* propToPick, QObject* obj, const char* slot)
    {
        ObjectSlot os;
        os.object = obj;
        os.slot = slot;
        PropMap.insert(propToPick, os);
    }

} // namespace pst
